/**************************************************************
          File Name:linked_list.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: 2015-02-07 10:35:05
***************************************************************/

#ifndef linked_list
#define linked_list
/* circular linked list with head pointer */
#include<stdio.h>
#include<stdlib.h>

#define OK      1
#define ERROR   0
typedef int status;

typedef struct list
{
    char data[10];
    struct list *next;
} List;

status init(List **head, int len)
{
    List *keep, *cur;
    int i;

    *head = (List *)malloc(sizeof(List));
    keep = *head;

    for(i = 0; i<len-1; i++)
    {
        cur = (List *)malloc(sizeof(List));
        if(!cur) return ERROR;
        keep->next = cur;
        keep = cur;
    }

    keep->next = *head;  // make a circular
    return OK;
}

void insert(List *head, List *value)
{
    value->next = head->next;
    head->next=value;
}

void rm(List **head)
{
    List *cur;

    cur = (*head)->next;
    *head = cur->next;
    free(cur);
}

void destroy(List *head)
{
    List *cur, *tmp;

    cur = head->next;
    while(cur != head)
    {
        tmp = cur;
        cur = cur->next;
        printf("free: %s\n", tmp->data);
        free(tmp);
    }
    printf("free head node: %s\n", cur->data);
    free(cur); // or free(head); free the head node
}

int listlen(List *head) // not include head node
{
    List *cur;
    int i;
    cur = head;
    for(i=0; cur!=head->next; i++)
        head = head->next;

    return i;
}

List *merge(List *one, List *two)
{
    List *tmp;

    tmp = one->next;
    one->next = two->next;
    two->next = tmp;

    return tmp;
}

#endif
